package com.amigo.online.message.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.amigo.online.message.mapper.online", sqlSessionTemplateRef  = "onlineSqlSessionTemplate")
public class OnlineDataSource {

    @Bean(name = "onlineData")
    @ConfigurationProperties(prefix = "spring.datasource.online") // application.properteis中对应属性的前缀
    public DataSource outData() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "onlineSqlSessionFactory")
    public SqlSessionFactory onlineSqlSessionFactory(@Qualifier("onlineData") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mybatis/mapper/online/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "onlineTransactionManager")
    public DataSourceTransactionManager onlineTransactionManager(@Qualifier("onlineData") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "onlineSqlSessionTemplate")
    public SqlSessionTemplate onlineSqlSessionTemplate(@Qualifier("onlineSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}